import { SUCCESS, staticURL, getStatistics, getGender, getCats, getCategories } from '@/api'

const state = () => ({
	// 大类别
	statistic: {},
	gender: {},

	//
	tabList:[],
	
})

const getters = {
}

const mutations = {
	updateStatistic (state, statistic) {
		state.statistic = statistic
	},
	updateGender (state, gender) {
		state.gender = gender
	},
	updateTabList (state, list) {
		state.tabList = list
	},

}

const actions = {
	
	// 1. 获取所有分类
	async getStatistics({dispatch, commit, state }) {
		const res = await getStatistics()
		console.log(res)
		if(res.ok){
			commit('updateStatistic', {
				female: {
					label: '女生',
					key: 'female',
					data: res.female
				},
				male: {
					label: '男生',
					key: 'male',
					data: res.male
				},
				picture: {
					label: '动漫',
					key: 'picture',
					data: res.picture
				},
				press: {
					label: '出版',
					key: 'press',
					data: res.press
				},
			})
			dispatch('setTabList')
		}
		
	},
	// 设置tabList
	setTabList({dispatch, commit, state }){
		const tabList = Object.keys(state.statistic).reduce((t,key,i)=>{
			state.statistic[key].data.forEach(el=>{
				el.bookCovers = el.bookCover.map(item=>{
					let url = staticURL + item
					// #ifdef MP-WEIXIN
					url = 'https:' + url
					// #endif
					return url
				})
			})
			const data = {
				pageid: i + 1,
				id: "tab" + i,
				name: state.statistic[key].label,
				key,
				statistics: state.statistic[key].data,
			}
			return t.concat(data)
		},[])
		commit('updateTabList', tabList)
	},
	// 2. 获取排行榜类型
	async getGender({dispatch, commit, state }) {
		const res = await getGender()
		console.log(res)
		if(res.ok){
			commit('updateGender', {
				epub: res.epub,
				female: res.female,
				male: res.male,
				picture: res.picture
			})
		}
		
	},
	
	// 4. 获取分类下小类别
	async getCats({dispatch, commit, state }) {
		const res = await getCats()
		console.log(res)
		// if(res.ok){
		// 	commit('updateGender', {
		// 		epub: res.epub,
		// 		female: res.female,
		// 		male: res.male,
		// 		picture: res.picture
		// 	})
		// }
		
	},
	
	// 5. 根据分类获取小说列表
	async getCategories({dispatch, commit, state }, data) {
		const res = await getCategories(data)
		console.log(88,res,staticURL)
		res.books.forEach(el=>{
			el.cover = staticURL + el.cover
			// #ifdef MP-WEIXIN
			el.cover =  'https:' + el.cover
			// #endif
		})
		return res

		// if(res.ok){
		// 	commit('updateGender', {
		// 		epub: res.epub,
		// 		female: res.female,
		// 		male: res.male,
		// 		picture: res.picture
		// 	})
		// }
		
	},
}

export default {
	namespaced: true,
	getters,
	state,
	mutations,
	actions
}
